<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="设备场地" prop="positionId">
            <el-select v-model="queryParams.positionId" placeholder="请选择" @keyup.enter="handleQuery" clearable="true">
              <el-option
                v-for="item in positionList"
                :key="item.positionId"
                :label="item.name"
                :value="item.positionId"
                :disabled="item.status == 'discard'"
              ></el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="场地管理员/代理商ID" prop="managerId">-->
<!--            <el-input v-model="queryParams.managerId" placeholder="请输入场地管理员/代理商ID" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="代理商ID" prop="parentManagerId">-->
<!--            <el-input v-model="queryParams.parentManagerId" placeholder="请输入代理商ID" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="固定费用" prop="fees">-->
<!--            <el-input v-model="queryParams.fees" placeholder="请输入固定费用" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="分润比例" prop="rate">-->
<!--            <el-input v-model="queryParams.rate" placeholder="请输入分润比例" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="代理商分润比例" prop="parentRate">-->
<!--            <el-input v-model="queryParams.parentRate" placeholder="请输入代理商分润比例" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="代理商费用" prop="parentFees">-->
<!--            <el-input v-model="queryParams.parentFees" placeholder="请输入代理商费用" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:managerConfig:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:managerConfig:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:managerConfig:remove']">删除</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:managerConfig:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="managerConfigList" border="true">
        <el-table-column label="#" type="index" width="55" align="center" fixed="left"/>
        <el-table-column label="ID" align="center" prop="managerConfigId" v-if="false" />
        <el-table-column label="场地ID" align="center" prop="positionId" v-if="false"/>
        <el-table-column label="场地名称" align="center" prop="positionName"/>
        <el-table-column label="代理商ID" align="center" prop="parentManagerId" v-if="false"/>
        <el-table-column label="代理商名称" align="center" prop="parentManagerUserName" />
        <el-table-column label="代理商分润比例" align="center" prop="parentRate" :formatter="parentRateFormatter"/>
        <el-table-column label="场地管理员" align="center" prop="managerId" v-if="false"/>
        <el-table-column label="场地管理员" align="center" prop="managerUserName"/>
        <el-table-column label="管理员分润比例" align="center" prop="rate" :formatter="percentFormatter"/>
        <el-table-column label="备注" align="center" prop="remark" />
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--          <template #default="scope">-->
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:managerConfig:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:managerConfig:remove']"></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改场地分润配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="managerConfigFormRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="设备场地" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择" :disabled="editable">
            <el-option
              v-for="item in positionList"
              :key="item.positionId"
              :label="item.name"
              :value="item.positionId"
              :disabled="item.status == 'discard'"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="代理商" prop="parentManagerId">
          <el-select v-model="form.parentManagerId" placeholder="请选择" clearable @change="handleAgentChange">
            <el-option
              v-for="item in agentList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
              :disabled="item.status === 0"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="代理商分润比例(%)" prop="parentRate" v-if="form.parentManagerId">
          <el-input-number v-model="form.parentRate" placeholder="分润比例"  :precision="2" min="0" max="100"/>
        </el-form-item>
        <el-form-item label="场地管理员" prop="managerId" v-if="userList.length>0">
          <el-select v-model="form.managerId" placeholder="请选择" clearable>
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
              :disabled="item.status === 0"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员分润比例(%)" prop="rate" v-if="userList.length>0">
          <el-input-number v-model="form.rate" placeholder="分润比例"  :precision="2" min="0" max="100"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ManagerConfig" lang="ts">
import { listManagerConfig, getManagerConfig, delManagerConfig, addManagerConfig, updateManagerConfig } from '@/api/device/managerConfig';
import { ManagerConfigVO, ManagerConfigQuery, ManagerConfigForm } from '@/api/device/managerConfig/types';
import {allPosition} from "@/api/device/position";
import {parsePercent} from "echarts/types/src/util/number";
import {allocatedUserList} from "@/api/system/role";
import {allUser, listUser} from "@/api/system/user";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const managerConfigList = ref<ManagerConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const editable = ref(false);

const queryFormRef = ref<ElFormInstance>();
const managerConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ManagerConfigForm = {
  managerConfigId: undefined,
  positionId: undefined,
  managerId: undefined,
  parentManagerId: undefined,
  shareType: undefined,
  fees: undefined,
  rate: undefined,
  parentShareType: undefined,
  parentRate: undefined,
  parentFees: undefined,
  remark: undefined
}
const data = reactive<PageData<ManagerConfigForm, ManagerConfigQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'create_time',
    isAsc: 'desc',
    positionId: undefined,
    managerId: undefined,
    parentManagerId: undefined,
    shareType: undefined,
    fees: undefined,
    rate: undefined,
    parentShareType: undefined,
    parentRate: undefined,
    parentFees: undefined,
    params: {
    }
  },
  positionList: [],
  agentList: [],
  userList: [],
  rules: {
    positionId: [
      { required: true, message: "场地ID不能为空", trigger: "blur" }
    ],
    managerId: [
      { required: true, message: "场地管理员", trigger: "blur" }
    ],
    // parentManagerId: [
    //   { required: true, message: "代理商ID不能为空", trigger: "blur" }
    // ],
    rate: [
      { required: true, message: "管理员分润比例不能为空", trigger: "blur" }
    ],
    parentRate: [
      { required: true, message: "代理商分润比例不能为空", trigger: "blur" }
      ]
  }
});

const { queryParams, form, rules,positionList,agentList,userList} = toRefs(data);

function percentFormatter(row){
  return row.rate + '%';
}
function parentRateFormatter(row){
  return row.parentRate + '%';
}

function handleAgentChange(val: any) {
  form.value.managerId = undefined;
  form.value.rate = undefined;
  let user = agentList.value.find(item => item.userId === val);
  if (user){
    //查询同部门的用户
    getUserListByDeptId(user.deptId,user.userId);
  }else {
    //查询全部用户
    getUserList();
  }
}

const getPositionList = async () => {
  loading.value = true;
  const res = await allPosition();
  positionList.value = res.data;
  loading.value = false;
}

/** 查询场地分润配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listManagerConfig(queryParams.value);
  managerConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  managerConfigFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ManagerConfigVO[]) => {
  ids.value = selection.map(item => item.managerConfigId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getUserList();
  dialog.visible = true;
  dialog.title = "添加场地分润配置";
  editable.value = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ManagerConfigVO) => {
  reset();
  const _managerConfigId = row?.managerConfigId || ids.value[0]
  const res = await getManagerConfig(_managerConfigId);
  if (res.data.parentManagerId){
    handleAgentChange(res.data.parentManagerId);
  }
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改场地分润配置";
  editable.value = true;
}

/** 提交按钮 */
const submitForm = () => {
  managerConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.managerConfigId) {
        await updateManagerConfig(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addManagerConfig(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ManagerConfigVO) => {
  const _managerConfigIds = row?.managerConfigId || ids.value;
  await proxy?.$modal.confirm('是否确认删除场地分润配置编号为"' + _managerConfigIds + '"的数据项？').finally(() => loading.value = false);
  await delManagerConfig(_managerConfigIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/managerConfig/export', {
    ...queryParams.value
  }, `managerConfig_${new Date().getTime()}.xlsx`)
}

/**
 * 查询代理商列表
 */
const getAgentList = async () => {
  loading.value = true;
  let queryParams ={"roleKey":"agent_role"};
  const res = await allocatedUserList(queryParams);
  agentList.value = res.rows;
  loading.value = false;
}

const getUserList = async () => {
  loading.value = true;
  const res = await allUser();
  loading.value = false;
  userList.value = res.rows;
}

const getUserListByDeptId = async (dept: any,userId: any) => {
  loading.value = true;
  const res = await listUser({"deptId":dept});
  loading.value = false;
  if (res.rows){
    let index = res.rows.findIndex(item => item.userId === userId);
    if (index !== -1) {
      res.rows.splice(index, 1);
    }
  }
  userList.value = res.rows;
}

onMounted(() => {
  getList();
  getPositionList();
  getAgentList();
  getUserList();
});
</script>
